package 顺序打印ABC;

import 顺序打印ABC.SynchronizedImpl;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Copyright (C) 2023 思创数码科技股份有限公司
 * <p/>
 * 版权所有
 * <p/>
 * 类名　　  : 顺序打印ABC.LockImpl
 * 功能概要  :
 *
 * @Author : yangwk
 * @Date : 2024/4/2 23:24
 */
public class LockImpl {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.submit(new ThreadA());
        executorService.submit(new ThreadB());
        executorService.submit(new ThreadC());
        Thread.currentThread().join(1000000);
    }

    static String threadNameA = "A";
    static String threadNameB = "B";
    static String threadNameC = "C";
    static Lock lock = new ReentrantLock();
    static final AtomicInteger atomicInteger1 = new AtomicInteger(1);

    static class ThreadA implements Runnable {
        @Override
        public void run() {
            while (true) {
                lock.lock();
                if (atomicInteger1.get() %3== 1) {
                    System.out.println(threadNameA);
                    atomicInteger1.incrementAndGet();
                }
                lock.unlock();
                System.out.println(atomicInteger1);
            }

        }
    }

    static class ThreadB implements Runnable {

        @Override
        public void run() {
            while (true) {
                lock.lock();
                if (atomicInteger1.get() %3== 2) {
                    System.out.println(threadNameB);
                    atomicInteger1.incrementAndGet();
                }
                lock.unlock();
                System.out.println(atomicInteger1);
            }
        }
    }

    static class ThreadC implements Runnable {

        @Override
        public void run() {
            while (true) {
                lock.lock();
                if (atomicInteger1.get() %3== 0) {
                    System.out.println(threadNameC);
                    atomicInteger1.incrementAndGet();
                }
                lock.unlock();
                System.out.println(atomicInteger1);
            }
        }
    }
}
